//
//  LEImagePickerTool.m
//  CreditAddressBook
//
//  Created by LE on 16/1/13.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "LEImagePickerTool.h"
#import "UIInfomationView.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "GKImageCropViewController.h"

//static LEHandlerBlock _imageBlock;

@interface LEImagePickerTool ()<GKImageCropControllerDelegate>

@end

@implementation LEImagePickerTool {
    LEHandlerBlock _imageBlock;
    BOOL _isEdit;
}

+ (instancetype)selectImageWithController:(UIViewController *)controller edit:(BOOL)isEdit completion:(LEHandlerBlock)completion {
    LEImagePickerTool *tool = [LEImagePickerTool shared];
    tool->_imageBlock = [completion copy];
    tool->_isEdit = isEdit;
    tool.originalImage = NO;
    [tool selectImgeWithController:controller];
    return tool;
}

+ (instancetype)select2ImageWithController:(UIViewController *)controller edit:(BOOL)isEdit completion:(LEHandlerBlock)completion {
     LEImagePickerTool *tool = [LEImagePickerTool shared];
     tool->_imageBlock = [completion copy];
     tool->_isEdit = isEdit;
     tool.originalImage = NO;
     [tool select2ImgeWithController:controller];
     return tool;
}

- (void)select2ImgeWithController:(UIViewController *)controller {
     [UIInfomationView showActionSheetInView:controller.view WithTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"相册",@"相机"] clickAtIndex:^(NSInteger buttonIndex) {
          switch (buttonIndex) {
               case 1:
                    //[self imageFromCameraWithController:controller];
                     [self imageFromPhotoLibraryWithController:controller];
                    break;
               case 2:
                    [self imageFromCameraWithController:controller];
                    
                    break;
               case 0:
                    _imageBlock = nil;
                    break;
               default:
                    break;
          }
     }];
}




+ (instancetype)shared {
    static LEImagePickerTool *tool;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tool = [[LEImagePickerTool alloc] init];
        [tool initData];
    });
    return tool;
}

- (void)initData {
    _cropSize = CGSizeMake(280, 280);
    _imageSize = CGSizeMake(800, 800);
}

- (void)selectImgeWithController:(UIViewController *)controller {
    [UIInfomationView showActionSheetInView:controller.view WithTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"相机"] clickAtIndex:^(NSInteger buttonIndex) {
        switch (buttonIndex) {
            case 1:
                [self imageFromCameraWithController:controller];
              // [self imageFromPhotoLibraryWithController:controller];
                break;
            case 2:
                
//                [self imageFromPhotoLibraryWithController:controller];

                break;
            case 0:
                _imageBlock = nil;
                break;
            default:
                break;
        }
    }];
}

#pragma mark -
/**
 *  从相机选取
 *
 *  @param con
 *  @param completion 
 */
- (void)imageFromCameraWithController:(UIViewController *)con {
    if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.sourceType = UIImagePickerControllerSourceTypeCamera;
//        controller.allowsEditing = _isEdit;
        if ([self isFrontCameraAvailable]) {
            controller.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        }
        NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
        [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
        controller.mediaTypes = mediaTypes;
        controller.delegate = self;
        [con presentViewController:controller animated:YES completion:nil];
    }
}
/**
 *  从相册选取
 *
 *  @param con
 *  @param completion
 */
- (void)imageFromPhotoLibraryWithController:(UIViewController *)con {
    if ([self isPhotoLibraryAvailable]) {
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//        controller.allowsEditing = _isEdit;
        NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
        [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
        controller.mediaTypes = mediaTypes;
        controller.delegate = self;
        [con presentViewController:controller animated:YES completion:nil];
    }
}
/**
 *  照片截取
 */
- (GKImageCropViewController *)imageCropWithImage:(UIImage *)image {
    GKImageCropViewController *cropController = [[GKImageCropViewController alloc] init];
//    cropController.contentSizeForViewInPopover = picker.contentSizeForViewInPopover;
    cropController.sourceImage = image;
    cropController.resizeableCropArea = NO;
    cropController.cropSize = self.cropSize;
    cropController.delegate = self;
    return cropController;
}

#pragma mark - 代理方法
/**
 *  代理方法
 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    if (_isEdit) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        CYLog(@"oldH:%f---oldW:%f", image.size.height, image.size.width);
        UIViewController *cropController = [self imageCropWithImage:image];
        [picker pushViewController:cropController animated:YES];
    } else {
        [picker dismissViewControllerAnimated:YES completion:^{
            if (_originalImage) {
                UIImage *portraitImg = [info objectForKey:UIImagePickerControllerOriginalImage];
                if (_imageBlock) {
                    _imageBlock(portraitImg);
                }
            } else {
                //对图片进行压缩
                UIImage *portraitImg = [info objectForKey:UIImagePickerControllerOriginalImage];
                CYLog(@"oldH:%f---oldW:%f", portraitImg.size.height, portraitImg.size.width);
                UIImage *newImage = [UIImage imageWithImage:portraitImg scaledToSize:self.imageSize];
                CYLog(@"height---%f, with---%f", newImage.size.height, newImage.size.width);
                if (_imageBlock) {
                    _imageBlock(newImage);
                }
            }
        }];
    }
}
/**
 *  GKImageCropControllerDelegate代理
 */
- (void)imageCropController:(GKImageCropViewController *)imageCropController didFinishWithCroppedImage:(UIImage *)croppedImage {
    [imageCropController dismissViewControllerAnimated:YES completion:^{
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];//防止拍照时状态栏隐藏出现的错误
        if (_originalImage) {
            CYLog(@"newH:%f---oldW:%f", croppedImage.size.height, croppedImage.size.width);
            if (_imageBlock) {
                _imageBlock(croppedImage);
            }
        } else {
            //对图片进行压缩
            CYLog(@"oldH:%f---oldW:%f", croppedImage.size.height, croppedImage.size.width);
            UIImage *newImage = [UIImage imageWithImage:croppedImage scaledToSize:self.imageSize];
            CYLog(@"height---%f, with---%f", newImage.size.height, newImage.size.width);
            if (_imageBlock) {
                _imageBlock(newImage);
            }
        }
    }];
}

#pragma mark -
- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}
@end
